<?php

namespace Frieza\Modules\Sysmsg\Controllers;

use Doraemon\tools\LinkFormat;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Doraemon\model\SearchKeyword;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;
use Doraemon\cache\SearchRecommendTag;
use Doraemon\cache\SearchTag;
use Doraemon\model\SysmsgTemplate;


class SysmsgTemplateController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    // 列表
    public function index(Request $request,Content $content) {
        $request_data = $request->all();

        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $itemLiist = SysmsgTemplate::select('*', [
            'ORDER' => ['id' => 'DESC'],
            'LIMIT' => [($page - 1) * $pageSize, $pageSize ],
        ]);
        $total = SysmsgTemplate::count('*');
        $gridModel = new pGridDataModel($itemLiist, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->column("id", 'ID');
                $grid->column("name", '名称');
                $grid->column("to_uid", '发送目标');
                $grid->column("from_uid", '发送者Uid');
                $grid->column("title", '标题');
                $grid->column("img", '图片')->image();
                $grid->column("link", '链接')->width(150);
                $grid->column("detail", '详情');
                $grid->column("msg_type", '消息类型');
                $grid->column("msg_code", '消息code码');
                $grid->column("unique_msg", '用户唯一');
                $grid->column("params", '必传参数');
                $grid->column("edit_time", '更新时间');
                $grid->column("status", '状态')->display(function () {
                    return SysmsgTemplate::STATUS_DESC[$this->status];
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                });
            });

        $tab = new Tab();
        $tab->add('系统消息模板列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('系统消息模板列表')
            ->description(' ')
            ->breadcrumb(['text' => '系统消息模板列表']);
    }

    // 编辑
    public function edit(Request $request,Content $content, $id = 0)
    {
        $request = $request->all();
        if($id == 0) {
            return $content
                ->header('系统消息模板 - 编辑')
                ->breadcrumb([
                    'text' => '系统消息模板',
                    'url' => '/sysmsg/SysmsgTemplate',
                ])
                ->body(self::editAction($request, $id , True));
        } else {
            return $content
                ->header('系统消息模板 - 编辑')
                ->breadcrumb([
                    'text' => '系统消息模板',
                    'url' => '/sysmsg/SysmsgTemplate',
                ])
                ->body(self::editAction($request, $id, False));
        }
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if(!$isCreate) {
            $data = SysmsgTemplate::get('*', ['id' => $id]);
            // 链接选择器
            $data['link'] = [
                'link_type' => $data['link_type'],
                'link_params' => $data['link_params'],
                'link_url' => $data['link'],
            ];
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $data = [];
            $form = new Form($data);
        }

        $form->text('name', '名称')->required('不能为空')->placeholder('模板名称');
        $form->select('msg_type', '消息类型')->options(SysmsgTemplate::MSG_TYPE_DESC)->required('不能为空');
        $form->radio('to_uid', '发送目标')->options([1 => '单个用户', 0 => '所有用户'])->default(1)->required('不能为空');
        $form->radio('unique_msg', '消息频次')->options([1 => '只发一次', 0 => '不限次数'])->default(0)->required('不能为空');
        $form->text('from_uid', '发送者Uid')->placeholder('发送者uid')->required('不能为空')->help("0：不指定发送者、其他：指定发送者");
        $form->text('msg_code', '消息code码')->default(SysmsgTemplate::getNextMsgCode())->readOnly()->required('不能为空');
        $form->text('title', '标题')->placeholder('标题');
        $form->text('img', '图片')->placeholder('图片地址');
        $form->text('link.link_url', '跳转链接(当前)')->placeholder('跳转链接')->readOnly();
        $form->multiLinkSelect("link", '跳转链接');
        $form->text('params', '自定义参数')->placeholder('自定义参数，用逗号分隔');
        $form->textarea('detail', '内容')->placeholder('内容');

        $form->action('/admin/sysmsg/SysmsgTemplate/save');

        return $form->render();
    }

    // 提交
    public function editSubmit(Request $request)
    {
        $request = $request->all();

        $data = [
            'name' => $request['name'],
            'to_uid' => $request['to_uid'],
            'from_uid' => $request['from_uid'],
            'title' => $request['title'],
            'img' => $request['img'],
            'link_type' => $request['link']['link_type'] ?? '',
            'link_params' => isset($request['link']['link_params']) ? json_encode($request['link']['link_params'], JSON_UNESCAPED_UNICODE) : '',
            'detail' => $request['detail'],
            'msg_type' => $request['msg_type'],
            'msg_code' => $request['msg_code'],
            'unique_msg' => $request['unique_msg'],
            'params' => $request['params'],
        ];
        if($data['link_type']) {
            $link = LinkFormat::generateLink($data['link_type'], $data['link_params']);
            $data['link'] = ($link && isset($link['app_template'])) ? $link['app_template'] : '';
        }

        $now = time();
        if(isset($request['id']) ) {
            $data['edit_time'] = date("Y-m-d H:i:s", $now);
            $id = $request['id'];
            $rs = SysmsgTemplate::updateInfo($id, $data);
        } else {
            $rs = SysmsgTemplate::addInfo($data);
        }

        if($rs) {
            if(isset($request['id'])) {
                $title = '修改成功';
            } else {
                $title = '添加成功';
            }

            $success = new MessageBag([
                'title' => $title
            ]);
            return redirect('/admin/sysmsg/SysmsgTemplate')->with(compact('success'));
        } else {
            if(isset($request['id'])) {
                $title = '修改失败';
            } else {
                $title = '添加失败';
            }
            $error = new MessageBag([
                'title' => $title
            ]);
            return back()->with(compact('error'));
        }
    }
}
